﻿#导入pygame库和一些常用的函数和常量
import pygame
from pygame.locals import *
import math
import random


#初始化pygame,创建一个窗口
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
#让兔子动起来
keys = [False,False,False,False]
playerpos=[100,100]
acc=[0,0]#射击精度
arrows=[]#记录所有的剑
#定义超过一定的时间，新建一只獾
badtimer=100
badtimer1=0
badguys=[[640,100]]
healthvalue=194
pygame.mixer.init()
clock = pygame.time.Clock()

#加载图片
start_screen = pygame.image.load('resources/images/ks.png')
pt = pygame.image.load('resources/images/pt.png')
kn = pygame.image.load('resources/images/kn.png')
zj = pygame.image.load('resources/images/zj.png')
tc1 = pygame.image.load('resources/images/tc1.png')
tc2 = pygame.image.load('resources/images/tc2.png')
player = pygame.image.load('resources/images/dude.png')
grass = pygame.image.load('resources/images/1.jpg')
grass1 = pygame.image.load('resources/images/2.png')
grass2 = pygame.image.load('resources/images/3.png')
castle = pygame.image.load('resources/images/castle.png')
castle = pygame.image.load("resources/images/castle.png")
arrow = pygame.image.load("resources/images/bullet.png")
#加载血条
healthbar = pygame.image.load("resources/images/healthbar.png")
health = pygame.image.load("resources/images/health.png")
#加载耗子图片
badguyimg1 = pygame.image.load("resources/images/badguy.png")
badguyimg=badguyimg1
#加载输赢图片
gameover = pygame.image.load("resources/images/gameover.png")
youwin = pygame.image.load("resources/images/youwin.png")

# 3.1 - 加载声音
hit = pygame.mixer.Sound("resources/audio/explode.wav")
enemy = pygame.mixer.Sound("resources/audio/enemy.wav")
shoot = pygame.mixer.Sound("resources/audio/shoot.wav")
hit.set_volume(0.05)
enemy.set_volume(0.05)
shoot.set_volume(0.05)

#开始界面鼠标检测
aging = 1
n = 1
while aging:
    clock.tick(30)
    buttons = pygame.mouse.get_pressed()
    x1, y1 = pygame.mouse.get_pos()  
    if x1 >= 240 and x1 <= 444 and y1 >= 120 and y1 <=174:
        if buttons[0]:
            aging = 0
    elif x1 >= 240 and x1 <= 444 and y1 >= 220 and y1 <=274:
        if buttons[0]:
            aging = 0
    elif x1 >= 240 and x1 <= 444 and y1 >= 320 and y1 <=374:
        if buttons[0]:
            aging = 0              
    elif x1 >= 200 and x1 <360 and y1 >= 420 and y1 <=474:
        start_screen.blit(tc2, (240, 420))
        if buttons[0]:
            pygame.quit()
            exit()
      
    else:
        start_screen.blit(pt, (240, 120))
        start_screen.blit(kn, (240, 220))
        start_screen.blit(zj, (240, 320))
        start_screen.blit(tc1, (240, 420))
        
        

    screen.blit(start_screen,(0,0))
    pygame.display.update()
    
    # 下面是监听退出动作
    # 监听事件
    for event in pygame.event.get(): 

        # 判断事件类型是否是退出事件
        if event.type == pygame.QUIT:
            print("游戏退出...")

            # quit 卸载所有的模块
            pygame.quit()

            # exit() 直接终止当前正在执行的程序
            exit()

#循环下列代码
running = 1
while running:
    #老鼠刷新
    badtimer-=0.5
    #给屏幕填充黑色
    screen.fill(0)
    #绘制草坪与布置兔窝
    if x1 >= 240 and x1 <= 444 and y1 >= 120 and y1 <=174:
        for x in range(width//grass.get_width()+1):
            for y in range(width//grass.get_height()+1):
                screen.blit(grass,(x*100,y*100))
    elif x1 >= 240 and x1 <= 444 and y1 >= 220 and y1 <=274:
        for x in range(width//grass1.get_width()+1):
            for y in range(width//grass1.get_height()+1):
                screen.blit(grass1,(x*100,y*100))
    elif x1 >= 240 and x1 <= 444 and y1 >= 320 and y1 <=374:
        for x in range(width//grass2.get_width()+1):
            for y in range(width//grass2.get_height()+1):
                screen.blit(grass2,(x*100,y*100))         

                
    screen.blit(castle,(0,30))
    screen.blit(castle,(0,135))
    screen.blit(castle,(0,240))
    screen.blit(castle,(0,345))
    #在屏幕上刷新兔子图片
    position = pygame.mouse.get_pos()
    angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26))
    playerrot = pygame.transform.rotate(player, 360-angle*57.29)
    playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2)
    screen.blit(playerrot, playerpos1)
    #画上箭头
    for bullet in arrows:
        index=0
        velx=math.cos(bullet[0])*10
        vely=math.sin(bullet[0])*10
        bullet[1]+=velx
        bullet[2]+=vely
        if bullet[1]<-64 or bullet[1]>640 or bullet[2]<-64 or bullet[2]>480:
            arrows.pop(index)
        index+=1
    for projectile in arrows:
        arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29)
        screen.blit(arrow1, (projectile[1], projectile[2]))
    if badtimer == 0:
        badguys.append([640, random.randint(50, 430)])
        badtimer = 100 - (badtimer1*2)
        if badtimer1 >= 35:
            badtimer1 = 35
        else:
            badtimer1 += 5
    index = 0
    #画上耗子
    for badguy in badguys:
        if badguy[0] < -64:
            badguys.pop(index)
        badguy[0] -= 1
        badrect = pygame.Rect(badguyimg1.get_rect())
        badrect.top = badguy[1]
        badrect.left = badguy[0]
        if badrect.left < 64:
            hit.play()
            healthvalue -= random.randint(5, 20)
            badguys.pop(index)
        index1 = 0
        #判断击中中老鼠
        for bullet in arrows:
            bullrect = pygame.Rect(arrow.get_rect())
            bullrect.left = bullet[1]
            bullrect.top = bullet[2]
            if badrect.colliderect(bullrect):
                enemy.play()
                acc[0] += 1
                badguys.pop(index)
                arrows.pop(index1)
            index1 += 1
        index += 1
    for badguy in badguys:
        screen.blit(badguyimg,badguy)

    #添加时钟用来计时
    font = pygame.font.Font("ziti/arial.ttf", 24)
    survivedtext = font.render(str((90000-pygame.time.get_ticks())//60000)+":"+
                               str((90000-pygame.time.get_ticks())//1000%60).zfill(2), True, (0,0,0))
    textRect = survivedtext.get_rect()
    textRect.topright = [635, 5]
    screen.blit(survivedtext, textRect)

    #添加生命条
    screen.blit(healthbar, (5,5)) 
    for health1 in range(healthvalue):
        screen.blit(health, (health1+8,8))
    
    #更新屏幕
    pygame.display.flip()
    #检查事件，如有退出命令，终止程序
    for event in pygame.event.get():
        #点击 X 按钮退出命令
        if event.type==pygame.QUIT:
            #退出游戏
            pygame.quit()
            exit(0)

        #按键检测
        if event.type == pygame.KEYDOWN:
            if event.key==K_w:
                keys[0]=True
            elif event.key==K_a:
                keys[1]=True
            elif event.key==K_s:
                keys[2]=True
            elif event.key==K_d:
                keys[3]=True
        if event.type == pygame.KEYUP:
            if event.key==pygame.K_w:
                keys[0]=False
            elif event.key==pygame.K_a:
                keys[1]=False
            elif event.key==pygame.K_s:
                keys[2]=False
            elif event.key==pygame.K_d:
                keys[3]=False
        #鼠标点击检测（射箭）
        if event.type==pygame.MOUSEBUTTONDOWN:
                position=pygame.mouse.get_pos()
                acc[1]+=1
                arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26))
                               ,playerpos1[0]+32,playerpos1[1]+32])
    #移动兔子
    if keys[0]:
        playerpos[1]-=5
    elif keys[2]:
        playerpos[1]+=5
    if keys[1]:
        playerpos[0]-=5
    elif keys[3]:
        playerpos[0]+=5
        
    #10 - 检查输赢
    if pygame.time.get_ticks() >= 90000:
        running = 0
        exitcode = 1
    if healthvalue <= 0:
        running = 0
        exitcode = 0
    if acc[1] != 0:
        accuracy = acc[0] * 1.0 / acc[1] * 100
    else:
        accuracy = 0

#11 - 输赢显示
if exitcode == 0:
    pygame.font.init()
    font = pygame.font.Font(None, 24)
    text = font.render("Accuracy: " + str(accuracy) + "%", True, (0, 0, 0))
    textRect = text.get_rect()
    textRect.centerx = screen.get_rect().centerx
    textRect.centery = screen.get_rect().centery + 70
    screen.blit(gameover, (0,0))
    screen.blit(text, textRect)

else:
    pygame.font.init()
    font = pygame.font.Font(None, 24)
    text = font.render("Accuracy: " + str(accuracy) + "%", True, (0, 0, 0))
    textRect = text.get_rect()
    textRect.centerx = screen.get_rect().centerx
    textRect.centery = screen.get_rect().centery + 70
    screen.blit(youwin, (0, 0))
    screen.blit(text, textRect)

while 1:
     for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit(0)
     pygame.display.flip()

